package com.order.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.servlet.http.HttpSession;

import com.order.config.Consts;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/** 
* @类名: CodeUtil 
* @描述: 产生验证码工具
* @作者: 林勃 
* @时间: 2014年4月25日 上午12:40:55 
*  
*/ 
public class CodeUtil {

	public static int width = 100;
	public static int height = 30;
	
	/** 
	* @Title: getNumber 
	* @描述: 随机产生验证码字符串
	* @param size
	* @return   
	*/ 
	public static String getNumber(int size) {
		String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
				+ "abcdefghijklmnopqrstuvwxyz";
		String number = "";
		Random r = new Random();
		for(int i=0;i<size;i++){
			number += chars.charAt(
					r.nextInt(chars.length()));
		}
		return number;
	}

	/** 
	* @Title: getCode 
	* @描述: 向输出流输入验证码
	* @param os   
	*/ 
	public static void getCode(OutputStream os, HttpSession session){
		//创建画布
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//获取画笔
		Graphics g = image.getGraphics();
		//给笔上颜色
		Random r = new Random();
		g.setColor(new Color(r.nextInt(255),
				r.nextInt(255),r.nextInt(255)));
		//给画布设置一个背景颜色  
		g.fillRect(0, 0, width, height);
		////将number绑订到session对象上

		String str = getNumber(5);
		session.setAttribute(Consts.CODE, str);
		System.out.println(str);
		//绘制
		g.setColor(new Color(0,0,0));
		g.setFont(new Font(null,Font.BOLD,15+r.nextInt(10)));
		g.drawString(str, 5, 25);

		//加一些干扰线
		for(int i=0;i<5;i++){
			g.drawLine(r.nextInt(width), r.nextInt(height), 
					r.nextInt(width), r.nextInt(height));
		}

		
		//压缩图片
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
		try {
			encoder.encode(image);
		} catch (ImageFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
